﻿namespace SemaphoreSlimTest
{
    internal class Program
    {
        readonly SemaphoreSlim semaphore = new(1, 1);
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
            SemaphoreSlimTest(new SemaphoreSlim(1, 1));
            Console.ReadLine();
        }

        /// <summary>
        /// Queues multiple tasks that each wait to enter the specified semaphore before executing their work
        /// asynchronously.
        /// </summary>
        /// <remarks>Each task waits asynchronously to enter the semaphore, performs its work, and then
        /// releases the semaphore. The degree of concurrency is limited by the initial count of the provided semaphore.
        /// This method is intended for demonstration or testing purposes and does not wait for all tasks to complete
        /// before returning.</remarks>
        /// <param name="semaphore">The SemaphoreSlim instance used to control concurrent access to the critical section. Cannot be null.</param>
        static void SemaphoreSlimTest(SemaphoreSlim semaphore)
        {
            int count = 10;
            while (count-- > 0)
            {
                Task.Run(async () =>
                {
                    if (await semaphore.WaitAsync(1000))//等待1秒钟,超时返回false
                    {
                        try
                        {
                            Console.WriteLine($"{Environment.CurrentManagedThreadId}:{count}");
                            await Task.Delay(5000);
                        }
                        finally
                        {
                            semaphore.Release();
                        }
                    }
                    else
                    {
                        Console.WriteLine($"等待超时:{Environment.CurrentManagedThreadId}:{count}");
                    }
                });
            }
        }
    }
}
